# -*- coding: utf-8 -*-
'''
@文件    :login.py
@说明    :
@时间    :2023/12/19 16:53:43
@作者    :浪晋
@版本    :1.0
'''

from flask import request,g
from utils.requetFunc import RequestParser
from utils.responseFunc import resultMsg
from utils.redisFunc import RedisDb as redis
from utils.jwtFunc import JWTManager as jwt
from app.admin import views
import datetime




@views.route("/login",methods=["post"])
def login():
    """
    @功能    :登录
    @参数    :
    @返回值  :
    @时间    :2022/12/29 00:07:38
    @作者    :浪晋
    @版本    :1.0
    """
    db = g.db
    ip = request.headers.get('X-Real-Ip') or request.remote_addr
    body = request.get_json()
    account = body.get("account")
    password = body.get("password")
    parse = RequestParser()
    parse.add_argument(value=account,name="账号",remark="不能为空",required=True,type=(str))
    parse.add_argument(value=password,name="密码",remark="不能为空",required=True,type=(str))
    parseMsg = parse.parse_args()
    if parseMsg:
        return resultMsg(code=0, msg=parseMsg)
    sql = "select a.id,a.account,a.nickName,a.status,a.phone,a.lastLoginIp,a.lastLoginTime,a.roleId,b.dataType from tb_system_user a join tb_system_role b on a.roleId = b.id where a.account ='{}' and a.password = '{}' and a.status != 0;".format(account,password)
    result = db.fetchone(sql)
    if not result:
        return resultMsg(code=0,msg="账号或者密码错误!")
    if result["status"] != 1:
        return resultMsg(code=0,msg="账号已被禁用!")
    data = {'lastLoginTime': datetime.datetime.now(),'lastLoginIp':ip}
    query = {"id":result.get("id")}
    db.update(table="tb_system_user",data=data,query=query)
    db.commit()
    token = jwt.generate(result)
    result.update({"token":token})
    redis().set_value(account,token)
    return resultMsg(msg="登录成功！",data=result)

